package com.woniuxy.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.woniuxy.entity.ResponseEntity;
import com.woniuxy.entity.User;
import com.woniuxy.service.UserService;
import com.woniuxy.utils.AlipayConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

/**
 * 以下所有功能原厂制造
 * @Author:吴毛伟
 */
@Controller
@RequestMapping("/alipay")
public class AlipayController{
    @Autowired
    private UserService userService;

    @RequestMapping("/pay")
    private void pay(String money, HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException, AlipayApiException {
        String totalprice = money;
        HttpSession session=req.getSession();
        User user=(User)session.getAttribute("user");
        int uid=user.getUid();
        // 获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id,
                AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key,
                AlipayConfig.sign_type);
        // 设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
        //由于异步回调会导致session消失
        String total_id=String.valueOf(uid);
        // 商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = "WN"+ UUID.randomUUID();
        // 付款金额，必填
        String total_amount = totalprice.toString();
        // 订单名称，必填
        String subject = "健身App充值订单";
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\"," + "\"total_amount\":\"" + total_amount
                + "\","+ "\"body\":\"" + total_id + "\"," + "\"subject\":\"" + subject + "\"," + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求
        String result = null;
        try {
            // 请求
            result = alipayClient.pageExecute(alipayRequest).getBody();
            // 设置响应类
            resp.setContentType("text/html;charset=utf-8");
            // 输出
            resp.getWriter().println(result);
        } catch (AlipayApiException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    @RequestMapping("/notify")
    private void donotify(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException, AlipayApiException {
        // 处理异步结果,适合处理后台数据
        // 获取支付宝POST过来反馈信息
            Map<String, String> params = new HashMap<String, String>();
            Map<String, String[]> requestParams = req.getParameterMap();
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
                }
                params.put(name, valueStr);
            }
            System.out.println(params+"-------------------------------------");
            boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key,
                    AlipayConfig.charset, AlipayConfig.sign_type); // 调用SDK验证签名
            // 验证成功
        //获取用户uid
            String total_id=new String(req.getParameter("body").getBytes("ISO-8859-1"),"UTF-8");
            int uid=Integer.parseInt(total_id);
            //获取交易的金额
            String out_total_amount = new String(req.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");
            // 交易状态
            String trade_status = new String(req.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
            if (trade_status.equals("TRADE_FINISHED")) {
            } else if (trade_status.equals("TRADE_SUCCESS")) {
                // 判断该笔订单是否在商户网站中已经做过处理
                // 如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                // 如果有做过处理，不执行商户的业务程序
                /* System.out.println("成功"); */
                //像用户进行添加money操作
                userService.updateUserMoney(uid,new BigDecimal(out_total_amount));
                // 支付业务操作
                // 注意：
                // 付款完成后，支付宝系统发送该交易状态通知
            }
        }

    @RequestMapping("/return")
    private ModelAndView doreturn(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.setViewName("redirect:/user/usercenter/index.html");
        return modelAndView;
    }
}

